package com.wonders.bigdata.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * Description: <br>
 *
 * @author: XB
 * @date: 2021/5/11 10:24
 */
public class GroupChatServer {
    // 定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    /**
     * 构造器
     * 初始化工作
     */
    public GroupChatServer() {
        try {
            // 得到选择器
            selector = Selector.open();
            // 得到监听连接通道
            listenChannel = ServerSocketChannel.open();
            // 设置监听端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置非阻塞模式
            listenChannel.configureBlocking(false);
            // 将listenChannel注册到selector中
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听
     */
    public void listen() {
        try {
            // 循环处理
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    // 有事件处理
                    // 遍历所有待处理的key
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        // 取出key
                        SelectionKey key = iterator.next();
                        // 监听到请求连接
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            // 将该通道注册到selector
                            sc.register(selector, SelectionKey.OP_READ);
                            // 提示
                            System.out.println(sc.getRemoteAddress() + " 上线");
                        }
                        // 监听到请求读取事件
                        if (key.isReadable()) {
                            // 处理读方法
                            readData(key);
                        }
                        // 最后将已经处理过的key移除，防止重复操作
                        iterator.remove();

                    }
                }else {
                    System.out.println("等待。。。");
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }

    /**
     * 读取客户端消息
     */
    private void readData(SelectionKey key) {
        // 定义一个socketChannel
        SocketChannel channel = null;
        try {
            // 得到channel
            channel = (SocketChannel) key.channel();
            // 创建buffter
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if (count > 0) {
                // 如果有消息
                String msg = new String(buffer.array());
                // 输出消息
                System.out.println("from 客户端：" + msg);
                // 向其他客户端发送消息，排除自己
                sendInfoToOtherClients(msg, channel);
            }
        }catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了。。。");
                // 取消注册
                key.cancel();
                // 关闭通道
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息。。。");
        // 遍历所有注册的通道
        for (SelectionKey key : selector.keys()) {
            // 获取key对应的通道
            Channel targetChannel = key.channel();
            // 判断通道类型及排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                // 转型
                SocketChannel dest = (SocketChannel) targetChannel;
                // 将消息加入缓存
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                // 将buffer数据写入通道
                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        // 创建一个服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
